<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="证书名称" prop="certificateName">
        <el-input
          v-model="queryParams.certificateName"
          placeholder="请输入证书名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证书类型" prop="certificateType">
        <el-select v-model="queryParams.certificateType" placeholder="请选择证书类型" clearable>
          <el-option
            v-for="dict in dict.type.iot_certificate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:certificate:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:certificate:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:certificate:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="certificateTable"
      v-loading="loading"
      :data="certificateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="证书名称" align="center" prop="certificateName"/>
      <el-table-column label="证书类型" align="center" prop="certificateType"/>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:certificate:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:certificate:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改证书对话框 -->
    <el-drawer
      :wrapperClosable="false"
      :title="title"
      :visible.sync="open"
      direction="rtl"
    >
      <el-container>
        <el-main>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">

            <!-- 证书名称 -->
            <el-form-item label="证书名称" prop="certificateName">
              <el-input v-model="form.certificateName" placeholder="请输入证书名称"/>
            </el-form-item>

            <!-- 证书类型 -->
            <el-form-item label="证书类型" prop="certificateType">
              <el-select v-model="form.certificateType" placeholder="请选择证书类型" class="select-width">
                <el-option
                  v-for="dict in dict.type.iot_certificate_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 密钥库 -->
            <el-form-item label="密钥库" prop="configuration.keystoreBase64">
              <el-input v-model="form.configuration.keystoreBase64" type="textarea"/>
              <input class="fileInput" type="file" @change="getBase64">
            </el-form-item>

            <!-- 密钥库密码 -->
            <el-form-item v-if="certificatePasswordVisible" label="密码" prop="configuration.keystorePwd">
              <el-input v-model="form.configuration.keystorePwd" placeholder="请输入密钥库密码"/>
            </el-form-item>

            <!-- 信任库 -->
            <el-form-item label="信任库" prop="configuration.trustKeyStoreBase64">
              <el-input v-model="form.configuration.trustKeyStoreBase64" type="textarea" placeholder="请填入信任库信息"/>
              <input class="fileInput" type="file" @change="getBase">
            </el-form-item>


            <!-- 信任库密码 -->
            <el-form-item v-if="certificatePasswordVisible" label="密码" prop="configuration.trustKeyStorePwd">
              <el-input v-model="form.configuration.trustKeyStorePwd" placeholder="请输入信任库密码"/>
            </el-form-item>

            <!-- 描述 -->
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>

          </el-form>

        </el-main>
        <el-footer>
          <div class="bottom-bar" style="text-align: right">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-drawer>

  </div>
</template>

<script>
import {
  addCertificate,
  editCertificate,
  getCertificate,
  listCertificate,
  removeCertificate
} from '@/api/iot/certificate'

export default {
  name: 'Certificate',
  dicts: ['iot_certificate_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书表格数据
      certificateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateName: null,
        certificateType: null
      },
      // 表单参数
      form: {
        configuration: {}
      },
      // 密码输入框默认隐藏
      certificatePasswordVisible: false,

      // 表单校验
      rules: {
        certificateName: [
          { required: true, message: '证书名称不能为空', trigger: 'blur' }
        ],
        certificateType: [
          { required: true, message: '证书状态不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'form.certificateType'(type) {
      this.visibleByCertificateType(type)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询证书列表 */
    getList() {
      this.loading = true
      listCertificate(this.queryParams).then(response => {
        this.certificateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        configuration: {},
        certificateName: null,
        certificateType: 'FEM',
        description: null
      }
      this.resetForm('form');
      // 清空文件输入框内容
      (document.getElementsByClassName('fileInput') || [])
        .forEach(input => input.value = '')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      selection.forEach(row => {
        if (row.publishState === 1) {
          this.$refs.certificateTable.toggleRowSelection(row)
        }
      })
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.certificateName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加证书'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getCertificate(id).then(response => {
        let data = response.data
        data.configuration = JSON.parse(data.configuration)
        this.form = data
        this.open = true
        this.title = '修改证书'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))
          form.configuration = JSON.stringify(form.configuration)
          if (this.form.id != null) {
            editCertificate(form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCertificate(form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.certificateName || this.names;
      this.$modal.confirm('是否确认删除证书名称为"' + names + '"的数据项？').then(() => {
        return removeCertificate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/certificate/export', {
        ...this.queryParams
      }, `certificate_${new Date().getTime()}.xlsx`)
    },
    /**
     * 根据证书类型显示隐藏表单
     * @param type 证书类型
     */
    visibleByCertificateType(type) {
      if (!type) {
        this.certificatePasswordVisible = false
        return
      }

      if (type === 'JKS') {
        this.certificatePasswordVisible = true
        return
      }

      if (type === 'PEM') {
        this.certificatePasswordVisible = false
        delete this.form.configuration.keystorePwd
        return
      }
      if (type === 'PFX') {
        this.certificatePasswordVisible = true
      }

    },

    getBase64(e) {
      // 选择的文件
      let file = e.target.files[0]
      if (!file) {
        return
      }
      // 判断文件是否读取完毕，读取完毕后执行
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        // 此处可对该base64进行获取赋值传入后端
        let result = e.target.result
        if (result.indexOf('base64') !== -1) {
          let arr = result.split(',')
          this.$set(this.form.configuration, 'keystoreBase64', arr[1])
        }
      }
    },

    getBase(e) {
      // 选择的文件
      let file = e.target.files[0]
      if (!file) {
        return
      }
      // 判断文件是否读取完毕，读取完毕后执行
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        // 此处可对该base64进行获取赋值传入后端
        let result = e.target.result
        if (result.indexOf('base64') !== -1) {
          let arr = result.split(',')
          this.$set(this.form.configuration, 'trustKeyStoreBase64', arr[1])
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
